package cn.cvs.controller;

import cn.cvs.pojo.TSysRole;
import cn.cvs.pojo.TSysUser;
import cn.cvs.service.SysUserService;
import cn.cvs.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Transactional
@Controller
@RequestMapping("/sys/user")
public class Ch10UserController {

    Logger logger =Logger.getLogger(Ch10UserController.class);

    @Resource
    SysUserService userService ;

    List<TSysRole> roleList;

    public Ch10UserController() {
        System.err.println(">>>>>>>>>>>>***************Ch10UserController");
        roleList =new ArrayList<TSysRole>(){
            {add(new TSysRole(1,"超级管理员"));}
            {add(new TSysRole(2,"店长"));}
            {add(new TSysRole(3,"店员"));}
        };

    }

    @RequestMapping("/list")
    public String toUserList(Model model
                            , @RequestParam(required = false) String queryRealName
                            , @RequestParam(required = false) String queryRoleId
                            , @RequestParam(defaultValue = "1") Integer pageIndex
    ){

        System.err.println(">>>>>>>>>>>>Ch10UserController.toUserList");
        //1.查询role的列表
        model.addAttribute("roleList",roleList);
        //2.查询用户列表
        Integer _roleId= Integer.valueOf(null==queryRoleId ? "0": queryRoleId);


        // 分页只要5条数据
        PageHelper.startPage(pageIndex, Constants.PAGE_SIZE);// limit x,x

        TSysUser param = new TSysUser(queryRealName,_roleId);//参数的查询对象

        List<TSysUser> userList = userService.getUserList(param);//获取到分页信息

        //把list对象,转换为Page分页对象
        PageInfo<TSysUser> page = new PageInfo<>(userList);

        model.addAttribute("page",page); //分页
       // model.addAttribute("userList",userList);
       /* model.addAttribute("queryRoleId",_roleId); //? 为了前端能得到上一次表单查询时提交的数据*/
        return "/sysUser/list.jsp";
    }

    @RequestMapping("/toAdd") //Get Post
    public String toAdd(){
        return "/sysUser/add.jsp";
    }

    @Transactional(propagation = Propagation.NESTED)
    @PostMapping("/add")  //Post
    public String userAdd(TSysUser sysUser
                        , HttpServletRequest request
                        ,@RequestParam(value = "attachs",required = false) MultipartFile[] attachs
            ){
        //添加成功
        //request.getParameter("account");
        System.out.println("-----------------UserController.userAdd: "+ sysUser);
        System.out.println("附件的数量: "+ attachs.length);

        try {
            //创建者id
            TSysUser loginUser = (TSysUser) request.getSession().getAttribute(Constants.userSession);//Obj -> user
            if(null !=loginUser){
                sysUser.setCreatedUserId(loginUser.getId());
            }
            //  statics/upload/xxxx.jpg
            String picDBPath ="/statics/uploads/";
            //文件上传
            // ① 引用 tomcat 中配了虚拟地址
            // ② 配置到当前项目的 项目根目录 statics/uploads中
            // 项目名+ "/statics/uploads/";
            String uploadPath = request.getSession().getServletContext().getRealPath(picDBPath);
            File file =new File(uploadPath);
            if (!file.exists()) {
                file.mkdir();
            }
            for (int i = 0; i < attachs.length; i++) {
                MultipartFile part = attachs[i];//取到单个的文件

                String fileName = part.getOriginalFilename();//原始的文件名称
                String uploadFileName =this.getFileName(fileName);// hsdfsdfa124234353sadf.jpg
                if (i==0){
                  //  sysUser.setIdPicPath(picDBPath.concat(uploadFileName)); //statics/uploads/文件名
                    sysUser.setIdPicPath("/statics/uploads/"+uploadFileName);
                }else {
                   // sysUser.setWorkPicPath(picDBPath.concat(uploadFileName));
                    sysUser.setWorkPicPath("/statics/uploads/"+uploadFileName);
                }
                //文件写入

                part.transferTo(new File(uploadPath.concat(uploadFileName)));
                //part.transferTo(new File("D:\\temp\\images\\"+uploadFileName));
            }
        } catch (Exception exception) {
           // exception.printStackTrace();

         //   System.out.println(exception.getMessage());
            throw new RuntimeException("添加新用户时,文件上传错误: "+exception.getMessage());
        }
        //添加到数据库
        System.out.println("-----------------UserController.userAdd>>> : "+ sysUser);

        int count =1;//userService.addUser(sysUser);
        if (count>0){
            return "redirect:/sys/user/list";
        }else{
            return "/sysUser/add.jsp";
        }

    }

    private String getFileName(String realFileName) {
        String uuid = UUID.randomUUID().toString();
        uuid =uuid.replace("-","");
        String ext =realFileName;
        ext =ext.substring(ext.lastIndexOf("."));
        return uuid+ext;
    }


    //查看用户信息

    //@RequestMapping("/view")
    //public String viewUser(Model model,@RequestParam Integer uid){   //RequestParam 参数来自request请求
    @ResponseBody  //ajax 请求
    //@RequestMapping(value = "/{uid}/view",produces = {"application/json;charset=utf-8"})//处理了响应的数据格式
    @RequestMapping(value = "/{uid}/view")//处理了响应的数据格式
    public Object viewUser(Model model
                        , @PathVariable  Integer uid
    ){  //PathVariable  参数来自 url(Path) 变量
        System.err.println(">>>>>>>>>>>>>>>Ch10UserController.viewUser   uid: "+ uid );
        //根据id查询数据 存 Model
        TSysUser user = userService.getUserList(new TSysUser(uid)).get(0);
      //  model.addAttribute("sysUser",user) ;//sysUser
      //  return "/sysUser/view.jsp";
        //return JSON.toJSONString(user);

        return user;
    }

   /* //局部的异常方法
    @ExceptionHandler(value ={RuntimeException.class} )
    public String handlerException(RuntimeException ex,HttpServletRequest request){
        //e.getMessage()
        request.setAttribute("e",ex);
        return "sysError.jsp";
    }*/

}
